package com.cw.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cw.pojo.TbGoods;
import com.cw.pojo.TbGoodsDesc;
import com.cw.pojo.TbItem;
import com.cw.service.FreemarkerService;
import com.cw.service.GoodService;
import com.cw.service.ItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FreemarkerServiceImpl implements FreemarkerService {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Reference
    private GoodService goodService;

    @Reference
    private ItemService itemService;

    @Override
    public void createItem(Long goodsId) throws IOException {

        Configuration configuration = freeMarkerConfigurer.getConfiguration();

        FileWriter fw = null;

        try {

            Template template = configuration.getTemplate("item.ftl");

            TbGoods goods = goodService.getGoods(goodsId);

            TbGoodsDesc goodsDesc = goodService.getGoodsDesc(goodsId);

            List<TbItem> itemList = itemService.getItem(goodsId);

            Map map = new HashMap();

            map.put("goods", goods);

            map.put("goodsDesc", goodsDesc);

            map.put("items", itemList);

            fw = new FileWriter("D:\\goods\\" + goodsId + ".html");

            template.process(map, fw);

        } catch (Exception e) {

            e.printStackTrace();

        }finally {

            if (fw != null) {

                fw.close();
            }
        }

    }
}
